import { updateQuestionUsingPost } from '@/api/questionController';
import { ProColumns, ProTable } from '@ant-design/pro-components';
import { message, Modal, Typography } from 'antd';
import React from 'react';


interface Props {
    oldData?: API.Question;
    visible: boolean;
    columns: ProColumns<API.Question>[];
    onSubmit: (values: API.QuestionAddRequest) => void;
    onCancel: () => void;
}

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.QuestionUpdateRequest) => {
    const hide = message.loading('正在更新');
    try {
        await updateQuestionUsingPost(fields);
        hide();
        message.success('更新成功');
        return true;
    } catch (error: any) {
        hide();
        message.error('更新失败，' + error.message);
        return false;
    }
};

/**
 * 更新弹窗
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<Props> = (props) => {
    const { oldData, visible, columns, onSubmit, onCancel } = props;

    if (!oldData) {
        return <></>;
    }
    const initValues={...oldData};
    if(oldData.tags){
        initValues.tags=JSON.parse(oldData.tags)||[];
    }

    return (
        <Modal
            className="update-modal"
            title={
                <Typography.Title level={3} style={{ margin: 0, color: '#262626' }}>
                    更新题目
                </Typography.Title>
            }
            open={visible}
            footer={null}
            onCancel={onCancel}
            width={800}
            destroyOnClose
        >
            <div className="modal-content-wrapper">
                <ProTable
                    type="form"
                    columns={columns}
                    form={{
                        initialValues: initValues,
                    }}
                    submitter={{
                        searchConfig: {
                            submitText: '确认更新',
                            resetText: '取消',
                        },
                        render: (_, dom) => <div className="form-actions">{dom}</div>,
                    }}
                    onSubmit={async (values: API.QuestionAddRequest) => {
                        const success = await handleUpdate({
                            ...values,
                            id: oldData.id as any,
                        });
                        if (success) {
                            onSubmit?.(values);
                        }
                    }}
                />
            </div>
        </Modal>
    );
};
export default UpdateModal;